import $ from "../bootstrap/$";

$.$define('getServerUserInfo', $.$promiseCache(function (data = {}, options = {}) {
	return $.$http.post('member/getInfo', data, options).then(function (res) {
		const user = res.data;
		if (user && user.bind_store_id) {
			wx.$setStoreId(user.bind_store_id);
		}

		return res.data || {};
	});
}));

$.$define('saveUserInfo', function (data, options = {}) {
	return $.$http.post('member/saveInfo', data, options).then(function (res) {
		if (res.data) {
			$.$getServerUserInfo.promise = Promise.resolve(res.data);
		} else {
			$.$getServerUserInfo.promise = null;
		}
		return res.data || {};
	});
});


/**
 * 绑定支付宝账号
 * @param {*} data
 * @param {*} options
 * @return {Promise<*>}
 */
$.$define('bindAlipayAccount', function (data, options = {}) {
	return wx.$http.post('member/bindalipayaccount', data, options).then(function (res) {
		$.$getServerUserInfo.promise = $.$getServerUserInfo.promise.then(function (res) {
			res.alipay_account = data.alipay_account;
			return res;
		});
		return res.data;
	});
});

$.$define('trySyncUserInfo', function () {
	return $.$getUserInfo().then(function (sysUserInfo) {
		return wx.$getServerUserInfo().then(function (res) {
			if (res.is_sync) {
				return res;
			}
			return wx.$saveUserInfo({
				nickname: sysUserInfo.nickName,
				avatar: sysUserInfo.avatarUrl,
				gender: sysUserInfo.gender,
				country: sysUserInfo.country,
				province: sysUserInfo.province,
				city: sysUserInfo.city,
				language: sysUserInfo.language,
			});
		});
	})
});

wx.$emitter.on('sys.getUserInfo.to', function () {
	wx.navigateTo({
		url: '/pages/user/auth/auth'
	})
});